package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Employee employee = UserContext.getCurrentUser();
        if (employee.isAdmin()){
            return true;
        }
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequiredPermission annotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);

        if (annotation == null) {
            return true;
        }

        List<String> stringList = UserContext.getStringList();
        String expressions = annotation.expression();

        if (stringList.contains(expressions)) {
            return true;
        }
        response.sendRedirect("/nopermission");
        return false;
    }
}
